<?php
// +----------------------------------------------------------------------
// | Category 类型服务
// +----------------------------------------------------------------------
// | 主要服务于Category数据处理
// +----------------------------------------------------------------------
// | 错误编码头 242xxx
// +----------------------------------------------------------------------

namespace common\service;

use common\exception\LogicException;
use common\model\AttributeValueModel;
use Exception;
use support\SingletonTrait;

class AttributeValueService
{

    use SingletonTrait;

    /**
     * 批量创建属性值
     * @param $dataList
     * @return bool
     * @throws Exception
     */
    public function saveBatch($dataList)
    {
        // 处理自定义字段
        $commonService = CommonService::instance("attribute_value");
        $commonService->setCurrentModuleCode("attribute_value");
        foreach ($dataList as &$data) {
            $data = $commonService->dealCreateCustomField($data, 'attribute_value');
            $data['uuid'] = create_uuid();
        }

        // 执行新增操作
        $attributeValueModel = model(AttributeValueModel::class);
        $attributeValueModel->startTrans();//强制开启事务

        try {
            $attributeAddData = $attributeValueModel->addAll($dataList);

            $attributeValueModel->commit();
            return $attributeAddData;
        } catch (\Throwable $e) {
            $attributeValueModel->rollback();
            throw $e;
        }
    }

    /**
     * 获取制作时长区间
     * 1、~3
     * 2、~6
     * 3、~9
     * 4、~12
     * 5、~15
     * 6、15~
     * @param $duration
     * @return string
     */
    public function getDurationAttribute($duration)
    {
        switch ($duration) {
            case $duration <= 3:
                return '~3';
            case $duration > 3 && $duration <= 6:
                return '~6';
            case $duration > 6 && $duration <= 9:
                return '~9';
            case $duration > 9 && $duration <= 12:
                return '~12';
            case $duration > 12 && $duration <= 15:
                return '~15';
            case $duration > 15:
                return '15~';
        }
    }

    /**
     * 查询属性值列表
     * @param $attributeIdList
     * @return array|false|mixed|string
     */
    public function getAttributeValueList($attributeIdList)
    {
        if (empty($attributeIdList)) {
            return [];
        }
        return model(AttributeValueModel::class)->where(['attribute_id' => ['IN', $attributeIdList]])->cache(C('database.default_query_cache_time'))->select();
    }

    /**
     * 查询属性值列表
     * @param $where
     * @param string $fields
     * @return array|false|mixed|string
     */
    public function getList($where, $fields = '*')
    {
        return model(AttributeValueModel::class)->where([$where])->field($fields)->cache(C('database.default_query_cache_time'))->select();
    }
}
